const axios = require("axios");
const { CONFIG } = require("./config");
/**
 * 获取token
 */
const getToken = async () => {
  const params = {
    grant_type: CONFIG.GRANT_TYPE,
    appid: CONFIG.APP_ID,
    secret: CONFIG.APP_SECRET,
  };

  const url = CONFIG.BASE_URL + CONFIG.TOKEN_API;

  return await axios.get(url, { params });
};

/**
 * 发送消息
 * @param {*} da
 * @returns
 */
const sendMsg = async (da) => {
  const token = (await getToken()).data.access_token;

  const data = {
    touser: CONFIG.USER_ID,
    template_id: CONFIG.TEMPLATE_ID,
    // 返回的数据 - 可以自定义
    data: da,
  };

  const url = CONFIG.BASE_URL + CONFIG.SEND_MSG_API + "?access_token=" + token;

  return await axios.post(url, data);
};

/**
 * 获取城市代码
 * @returns
 */
async function getLocationID() {
  const url = "https://geoapi.qweather.com/v2/city/lookup";
  const params = {
    key: CONFIG.HEFENG_API_KEY,
    location: CONFIG.CITY,
  };
  return await axios.get(url, { params });
}

/**
 * 天气状况
 */
async function getWeather() {
  const locationID = (await getLocationID()).data.location[0].id;

  const url = "https://devapi.qweather.com/v7/weather/now";

  const params = {
    key: CONFIG.HEFENG_API_KEY,
    location: locationID,
  };

  return await axios.get(url, { params });
}

/**
 * 彩虹屁
 */
async function getWords() {
  const url = "https://api.shadiao.pro/chp";
  return await axios.get(url);
}

module.exports = {
  sendMsg,
  getWeather,
  getWords,
};
